#!/usr/bin/env bash

. ./test.common

test_start "source selection"

# Falsetickers should be detected if their number is less than half of all

base_delay=1e-3
servers=5

for falsetickers in 1 2; do
	run_test || test_fail
	check_chronyd_exit || test_fail
	check_source_selection || test_fail
	check_packet_interval || test_fail
	check_sync || test_fail
done

for falsetickers in 3 4; do
	run_test || test_fail
	check_chronyd_exit || test_fail
	check_packet_interval || test_fail
	# These check are expected to fail
	check_source_selection && test_fail
	check_sync && test_fail

	if [ $falsetickers = 3 ]; then
		check_log_messages "Can't synchronise: no majority (only 2 of 5 sources agree)" 1 1 || test_fail
	else
		check_log_messages "Can't synchronise: no majority (no agreement among 5 sources)" 1 1 || test_fail
	fi
done

# Sources with large asymmetric delay should be excluded

servers=3
falsetickers=0
base_delay="(+ 1e-3 (equal 0.1 to 2) (equal 0.1 to 3))"

run_test || test_fail
check_chronyd_exit || test_fail
check_source_selection || test_fail
check_sync || test_fail

# Sources with large distance should be ignored

servers=1
server_strata=2
server_conf="maxclockerror 1000"
jitter=1e-7
base_delay="(* -1.0 (equal 0.1 (min time 600) 600) (equal 0.1 from 2) (equal 0.1 to 1))"

run_test || test_fail
check_chronyd_exit || test_fail
check_packet_interval || test_fail
check_source_selection && test_fail
check_sync && test_fail

check_log_messages "Root distance of 192\.168\.123\.2 exceeds maxdistance of 3\." 1 1 || test_fail

# Sources with large jitter should be ignored

server_strata=1
server_conf=$default_server_conf
server_step="(pulse 64 64)"
base_delay=$default_base_delay

run_test || test_fail
check_chronyd_exit || test_fail
check_packet_interval || test_fail
check_source_selection && test_fail
check_sync && test_fail

check_log_messages "Jitter of 192\.168\.123\.1 exceeds maxjitter of 1\." 1 1 || test_fail

test_pass
